package com.bawei.common.mvi

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bawei.common.base.BaseFragment
import kotlinx.coroutines.launch

/**
 * Author: Jason Zhang
 * Date: 2024/8/19
 * Desc: MVI模式下的BaseFragment
 */
abstract class BaseMviFragment<T: ViewDataBinding>:BaseFragment<T>() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        var rootView = super.onCreateView(inflater, container, savedInstanceState)
        initData()
        updateUi()
//        EventBus.getDefault().register(this)
        return rootView
    }

    //定义一个接收EventBus消息的方法
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    fun receiveEvent(event: CustomEvent){
//        if (event != null && event.target == this::class.java.simpleName){
//            handEvent(event)
//        }
//    }

    //处理EventBus消息
//    open fun handEvent(event: CustomEvent){
//
//    }

    override fun onDestroyView() {
//        EventBus.getDefault().unregister(this)
        super.onDestroyView()
    }

    private fun initData(){
        //启动协程给ViewModel发送意图Intent
        lifecycleScope.launch {
            sendViewIntent()
        }
    }

    private fun updateUi(){
        //启动协程更新UI
        lifecycleScope.launch {
            //当Activity处于STARTED状态时接收状态更新UI
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
                collectUiState()
            }
        }
    }

    open suspend fun sendViewIntent(){

    }

    open suspend fun collectUiState(){

    }









}